package com.navi.mould1.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class DownLoad {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    //$("#fileName").val("User.xlsx");
    @RequestMapping(value = "/download.action")
    public String downloadFile(@RequestParam("fileName") String fileName,
                               HttpServletRequest request, HttpServletResponse response) {
        if (fileName != null) {
//			             String realPath = request.getServletPath().getRealPath(
//			                     "WEB-INF/File/");
            File file = new File("F:/opt/qms/excel/" + fileName);
            if (!file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    @RequestMapping(value = "/eqcs/export")
    public void downloadEQCSModel(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException {
        String file_name = "机台接触点位模板.xlsx"; //要下载的文件名
        if(file_name == null){
            file_name="";
        }
        String filePath = "/dfs/oc/QMS/Template";
        String temp1 = File.separator;//路径分隔符("\\")
        String url = filePath + temp1 + file_name;
//        String url = session.getServletContext().getRealPath("/") + "excelFile\\机台接触脚位模板.xlsx";
        System.out.println("filedownload =" + url);
        export(request, response,url,file_name);


    }

    @RequestMapping(value = "/defectCode/export")
    public void downloadDefectCodeModel(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException {
        String file_name = "DefectCode模板.xlsx"; //要下载的文件名
        if(file_name == null){
            file_name="";
        }

        String filePath = "/dfs/oc/QMS/Template";
//        String realpath = request.getSession().getServletContext().getRealPath("/");//获取服务器的物理路径
        String temp1 = File.separator;//路径分隔符("\\")
        String url = filePath + temp1 + file_name;//要提供下载的文件的物理路径＋文件名
//        String url = session.getServletContext().getRealPath("/") + "excelFile\\DefectCode模板.xlsx";
        System.out.println("filedownload =" + url);
        export(request, response,url,file_name);
    }

    public void export(HttpServletRequest request, HttpServletResponse response,String url,String fileName) throws IOException{
        response.setContentType("application/octet-stream");
        if (request.getHeader("user-agent").toLowerCase().indexOf("firefox") > -1) {
            //火狐浏览器自己会对URL进行一次URL转码所以区别处理
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName,"utf-8"));        }
        //新建文件输入输出流
        OutputStream output = null;
        FileInputStream fis = null;
        try{

            File f = new File(url);//新建File对象
            output = response.getOutputStream();//新建文件输入输出流对象
            fis = new FileInputStream(f);
            byte[] b = new byte[(int)f.length()]; //设置每次写入缓存大小

            //把输出流写入客户端
            int i = 0;
            while((i = fis.read(b)) > 0){
                output.write(b, 0, i);
            }
            output.flush();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally
        {
            if(fis != null)
            {
                fis.close();
                fis = null;
            }
            if(output != null)
            {
                output.close();
                output = null;
            }
        }
    }
}